#!/sbin/openrc-run
# Copyright 1999-2014 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2


# We do not give a choice to user for configuring these 'cause it will mess up
# Webmin's configuration
WEBMIN_EXE="%exe%"
WEBMIN_PID="%pid%"
WEBMIN_CONF="%conf%"
WEBMIN_CONFIG="%config%"

extra_started_commands="reload"

depend() {
	use net logger
}

checkconfig() {
	# Check if Webmin setup has been done
	if [ ! -f ${WEBMIN_CONFIG} ]; then
		eerror "Error in Webmin's configuration. The ${WEBMIN_CONFIG} is not present."
		eerror "Please run 'emerge --config app-admin/webmin' to fix this."
		return 1
	fi

	# Check if ssl cert is present
	local key ssl
	key=`grep "^keyfile=" ${WEBMIN_CONF} | sed -e 's/keyfile=//g'`
	ssl=`grep "^ssl=" ${WEBMIN_CONF} | sed -e 's/ssl=//g'`

	if [ ! -f "${key}" ] ; then
		if [ "${ssl}" = "0" ]; then
			ewarn "Your SSL certificate is not present."
			ewarn "Please either fix the path in the 'keyfile=' option of your ${WEBMIN_CONF}"
			ewarn "OR run 'emerge --config app-admin/webmin'"
		else
			eerror "Error in Webmin's configuration. No SSL certificate is present."
			eerror "Please either fix the path in the 'keyfile=' option of your ${WEBMIN_CONF}"
			eerror "OR change the 'ssl=' option of your ${WEBMIN_CONF} to 'ssl=0'"
			eerror "OR run 'emerge --config app-admin/webmin'"
			return 1
		fi
	fi

	return 0
}

reload() {
	if [ ! -f "${WEBMIN_PID}" ]; then
		eerror "Webmin is not running"
		return 1
	fi

	checkconfig || return 1

	ebegin "Reloading Webmin's configuration files"
	start-stop-daemon --signal USR1 --pidfile "$WEBMIN_PID"
	eend $?
}

start() {
	checkconfig || return 1
	ebegin "Starting Webmin"

	start-stop-daemon --start --background --interpreted \
		--env LANG= \
		--env PERLLIB="%perllib%" \
		--exec "$WEBMIN_EXE" \
		--pidfile "$WEBMIN_PID" \
		-- "$WEBMIN_CONF"
	eend $?
	# Leave time to spawn, so no stop is received while spawning
	sleep 3
}

stop() {
	ebegin "Stopping Webmin"
	start-stop-daemon --stop  --interpreted --quiet \
		--exec "$WEBMIN_EXE" \
		--pidfile "$WEBMIN_PID"
	eend $?
	# Leave time to stop because of the scripts that use this
	sleep 3
}
